package com.example.dao;

import com.example.bean.Resident;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ResidentDAO {
    private static final Logger logger = Logger.getLogger(ResidentDAO.class.getName());

    // 登记居民信息
    public boolean registerResident(Resident resident) {
        String sql = "INSERT INTO residents (name, gender, birth_date, address, health_status) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, resident.getName());
            pstmt.setString(2, resident.getGender());
            pstmt.setTimestamp(3, new java.sql.Timestamp(resident.getBirthDate().getTime()));
            pstmt.setString(4, resident.getAddress());
            pstmt.setString(5, resident.getHealthStatus()); // 新增健康状态设置
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "登记居民信息时发生 SQL 异常，SQL 语句: " + sql, e);
            return false;
        }
    }

    // 修改居民信息
    public boolean updateResident(Resident resident) {
        String sql = "UPDATE residents SET name = ?, gender = ?, birth_date = ?, address = ?, health_status = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, resident.getName());
            pstmt.setString(2, resident.getGender());
            pstmt.setTimestamp(3, new java.sql.Timestamp(resident.getBirthDate().getTime()));
            pstmt.setString(4, resident.getAddress());
            pstmt.setString(5, resident.getHealthStatus()); // 新增健康状态设置
            pstmt.setInt(6, resident.getId());
            int rowsAffected = pstmt.executeUpdate();
            logger.info("执行更新操作，SQL 语句: " + sql + "，影响行数: " + rowsAffected);
            return rowsAffected > 0;
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "修改居民信息时发生 SQL 异常，SQL 语句: " + sql, e);
            // 打印详细异常信息
            e.printStackTrace();
            return false;
        }
    }
    // 查找居民信息
    public List<Resident> searchResidents(String keyword) {
        List<Resident> residentList = new ArrayList<>();
        String sql = "SELECT * FROM residents WHERE name LIKE ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, "%" + keyword + "%");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Resident resident = new Resident();
                resident.setId(rs.getInt("id"));
                resident.setName(rs.getString("name"));
                resident.setGender(rs.getString("gender"));
                resident.setBirthDate(rs.getTimestamp("birth_date"));
                resident.setAddress(rs.getString("address"));
                resident.setHealthStatus(rs.getString("health_status")); // 新增健康状态获取
                residentList.add(resident);
            }
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "查找居民信息时发生 SQL 异常，SQL 语句: " + sql, e);
        }
        return residentList;
    }

    // 删除居民信息
    public boolean deleteResident(int id) {
        String sql = "DELETE FROM residents WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            logger.info("执行删除操作，SQL 语句: " + sql + "，参数: id = " + id);
            pstmt.setInt(1, id);
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                logger.info("成功删除居民信息，id = " + id);
            } else {
                logger.warning("未找到要删除的居民信息，id = " + id);
            }
            return rowsAffected > 0;
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "删除居民信息时发生 SQL 异常，SQL 语句: " + sql + "，参数: id = " + id, e);
            return false;
        }
    }
    // 获取所有居民信息
    public List<Resident> getAllResidents() {
        String sql = "SELECT * FROM residents";
        List<Resident> residentList = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            logger.info("执行查询所有居民信息操作，SQL 语句: " + sql);
            while (rs.next()) {
                Resident resident = new Resident();
                resident.setId(rs.getInt("id"));
                resident.setName(rs.getString("name"));
                resident.setGender(rs.getString("gender"));
                resident.setBirthDate(rs.getTimestamp("birth_date"));
                resident.setAddress(rs.getString("address"));
                resident.setHealthStatus(rs.getString("health_status")); // 新增健康状态获取
                residentList.add(resident);
            }
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "获取所有居民信息时发生 SQL 异常，SQL 语句: " + sql, e);
        }
        return residentList;
    }

    // 根据居民 ID 获取居民信息
    public Resident getResidentById(int id) {
        String sql = "SELECT * FROM residents WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                Resident resident = new Resident();
                resident.setId(rs.getInt("id"));
                resident.setName(rs.getString("name"));
                resident.setGender(rs.getString("gender"));
                resident.setBirthDate(rs.getTimestamp("birth_date"));
                resident.setAddress(rs.getString("address"));
                resident.setHealthStatus(rs.getString("health_status")); // 新增健康状态获取
                return resident;
            }
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "根据居民 ID 获取居民信息时发生 SQL 异常，SQL 语句: " + sql + "，参数: id = " + id, e);
        }
        return null;
    }

    public void updateResident(HttpServletRequest request, HttpServletResponse response) {
    }
}